package com.minelx.datamicroscope.core.query.literalcondition;

import com.alibaba.fastjson.JSONObject;
import com.minelx.datamicroscope.core.query.AliasedKey;
import com.minelx.datamicroscope.core.values.CommonField;

import java.util.List;

import static java.util.stream.Collectors.toList;

class ContentAndFieldLiteralConditionParser implements LiteralConditionParser {
    ContentAndFieldLiteralConditionParser() {
    }

    @Override
    public boolean match(JSONObject data) {
        return data.containsKey("content") && data.containsKey("field");
    }

    @Override
    public LiteralCondition createLiteralCondition(JSONObject data) {
        String content = data.getString("content");
        JSONObject fieldDescription = data.getJSONObject("field");
        return LiteralCondition.contentAndField(
                content,
                fieldDescriptionToAliasedKeys(fieldDescription));
    }

    private static List<AliasedKey> fieldDescriptionToAliasedKeys(JSONObject fieldDescription) {
        return fieldDescription.entrySet().stream()
                .map(stringObjectEntry -> AliasedKey.create(stringObjectEntry.getKey(), CommonField.from((String) stringObjectEntry.getValue())))
                .collect(toList());
    }
}
